package com.shroo8.footballblog.controllers.twitter;

import java.io.IOException;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;

@Controller
@Scope("session")
public class SigninController {

	private static final Logger logger = LoggerFactory.getLogger(SigninController.class);
	
	@Resource(name="twitter")
	Twitter twitter;
	
	@RequestMapping(value = "/signin", method = RequestMethod.GET)
	public void signin(Locale locale, HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		logger.info("Welcome to twitter signin! The client locale is {}.", locale);
		
		
		String redirectUrl = request.getParameter("redirectUrl");

		request.getSession().setAttribute("twitter", twitter);
		request.getSession().setAttribute("redirectUrl", redirectUrl);

        try {
            StringBuffer callbackURL = request.getRequestURL();
            int index = callbackURL.lastIndexOf("/");
            callbackURL.replace(index, callbackURL.length(), "").append("/callback");

            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
            request.getSession().setAttribute("requestToken", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());

        } catch (TwitterException e) {
            throw new ServletException(e);
        }
	}
	
	public Twitter getTwitter() {
		return twitter;
	}

	public void setTwitter(Twitter twitter) {
		this.twitter = twitter;
	}

}
